/*
 * Pesquisa.java
 *
 * Created on 01/11/2009, 21:32:09
 */
package bil.gui;

import bil.Config;
import bil.imagem.*;
import bil.busca.Buscador;
import bil.busca.HTMLFormComponents;
import bil.download.Atualizador;
import bil.download.Downloader;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JFileChooser;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

/**
 *
 * @author Eduardo Folly
 */
public class Pesquisa extends javax.swing.JInternalFrame {
    /*
    private final String p1 = "http://images.google.com.br/images?as_q=%i%&hl=pt-BR" +
    "&safe=off&start=%s%&ndsp=20";
     */

    private ImagemModel imagens = new ImagemModel();
    private int tempRow = -1;

    /** Creates new form Pesquisa */
    public Pesquisa() {
        initComponents();
        botaoLimparActionPerformed(null);
        Config.getDesktop().add(this);
        try {
            this.setMaximum(true);
            campoPastaPadrao.setText(Config.getInstance().getPastaPadrao());
            editorHtml.setPage(this.getClass().getResource("/bil/busca/exemplo.html"));
        } catch (Exception e) {
        }
        this.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        campoPesquisa = new javax.swing.JTextField();
        botaoPesquisar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        campoQtdImagens = new javax.swing.JFormattedTextField();
        botaoLimpar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        campoPastaPadrao = new javax.swing.JTextField();
        botaoProcurar = new javax.swing.JButton();
        botaoFechar = new javax.swing.JButton();
        botaoBaixar = new javax.swing.JButton();
        barra = new javax.swing.JProgressBar();
        jLabel4 = new javax.swing.JLabel();
        labelVelocidade = new javax.swing.JLabel();
        painelTabulado = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaImagens = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        editorHtml = new javax.swing.JEditorPane();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Pesquisa");

        jLabel1.setText("Pesquisar:");

        campoPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                campoPesquisaKeyReleased(evt);
            }
        });

        botaoPesquisar.setText("Pesquisar");
        botaoPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoPesquisarActionPerformed(evt);
            }
        });

        jLabel2.setText("Qtd. Imagens:");

        campoQtdImagens.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        campoQtdImagens.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        campoQtdImagens.setText("50");
        campoQtdImagens.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                campoQtdImagensKeyReleased(evt);
            }
        });

        botaoLimpar.setText("Limpar");
        botaoLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoLimparActionPerformed(evt);
            }
        });

        jLabel5.setText("Salvar em:");

        campoPastaPadrao.setEnabled(false);

        botaoProcurar.setText("Procurar");
        botaoProcurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoProcurarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(campoQtdImagens, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoPastaPadrao, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoProcurar))
                    .addComponent(campoPesquisa, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 519, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(botaoLimpar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(botaoPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(botaoPesquisar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoQtdImagens, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5)
                    .addComponent(campoPastaPadrao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botaoProcurar)
                    .addComponent(botaoLimpar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        botaoFechar.setText("Fechar");
        botaoFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoFecharActionPerformed(evt);
            }
        });

        botaoBaixar.setText("Baixar");
        botaoBaixar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoBaixarActionPerformed(evt);
            }
        });

        barra.setStringPainted(true);

        jLabel4.setText("Velocidade:");

        labelVelocidade.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        labelVelocidade.setText("0 Kb/s");

        tabelaImagens.setModel(imagens);
        tabelaImagens.setToolTipText("Teste");
        tabelaImagens.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
        tabelaImagens.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaImagensMouseClicked(evt);
            }
        });
        tabelaImagens.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                tabelaImagensMouseMoved(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaImagens);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 706, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
                .addContainerGap())
        );

        painelTabulado.addTab("Imagens", jPanel2);

        editorHtml.setContentType("text/html"); // NOI18N
        editorHtml.setEditable(false);
        jScrollPane2.setViewportView(editorHtml);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 706, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
                .addContainerGap())
        );

        painelTabulado.addTab("Avançado", jPanel3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelVelocidade, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 413, Short.MAX_VALUE)
                .addComponent(botaoBaixar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botaoFechar)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(barra, javax.swing.GroupLayout.DEFAULT_SIZE, 731, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(painelTabulado, javax.swing.GroupLayout.DEFAULT_SIZE, 767, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(painelTabulado, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(barra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoFechar)
                    .addComponent(botaoBaixar)
                    .addComponent(jLabel4)
                    .addComponent(labelVelocidade))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaImagensMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaImagensMouseClicked
        if (evt.getClickCount() == 1) {
            int row = tabelaImagens.rowAtPoint(new Point(evt.getX(), evt.getY()));
            int col = tabelaImagens.columnAtPoint(new Point(evt.getX(), evt.getY()));
            if (col == 1) {
                tabelaImagens.getModel().setValueAt(!((Boolean) tabelaImagens.getModel().getValueAt(row, col)), row, col);
                tabelaImagens.repaint();
            }
            evt.consume();
        }

        if (evt.getClickCount() == 2) {
            evt.consume();
            this.botaoBaixarActionPerformed(null);
            return;
        }
    }//GEN-LAST:event_tabelaImagensMouseClicked

    private void botaoPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoPesquisarActionPerformed
        try {
            botaoLimparActionPerformed(evt);
            String id = campoPesquisa.getText();
            id = URLEncoder.encode(id, "UTF-8");

            int ini = 0; //Integer.parseInt(campoStart.getText());
            int qtd = Integer.parseInt(campoQtdImagens.getText());

            HTMLFormComponents comp = new HTMLFormComponents(editorHtml);
            List lista = comp.searchFormComp();

            lista.remove("hl");
            lista.remove("as_st");

            lista = comp.getValues();

            lista.add("hl=pt-BR");
            lista.add("as_st=y");
            lista.add("btnG=Pesquisa+Google");

            String qs = "";
            for (Object o : lista) {
                qs += "&" + o.toString();
            }

            if (qs.indexOf("&as_q=") < 0) {
                if (!id.isEmpty()) {
                    qs += "&as_q=" + id;
                } else {
                    return;
                }
            }

            qs = qs.substring(1);

            String endereco = "http://images.google.com.br/images?" + qs;

//            System.out.println(endereco);

            painelTabulado.setSelectedIndex(0);

            ExecutorService tpes = Executors.newFixedThreadPool(1);
            Buscador google = new Buscador(barra, endereco, ini, qtd, tabelaImagens);

            tpes.execute(google);

            tpes.shutdown();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_botaoPesquisarActionPerformed

    private void botaoBaixarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoBaixarActionPerformed
        int pool = Config.getInstance().getQtdThreads();

        ExecutorService tpes = Executors.newFixedThreadPool(2);

        Atualizador atua = new Atualizador(tabelaImagens, labelVelocidade, botaoBaixar);
        tpes.execute(atua);

        tpes.execute(new Downloader(tabelaImagens, barra, campoPastaPadrao.getText(), pool, atua));

        tpes.shutdown();
    }//GEN-LAST:event_botaoBaixarActionPerformed

    private void campoPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoPesquisaKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            evt.consume();
            this.botaoPesquisarActionPerformed(null);
        }
    }//GEN-LAST:event_campoPesquisaKeyReleased

    private void campoQtdImagensKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoQtdImagensKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            evt.consume();
            this.botaoPesquisarActionPerformed(null);
        }
    }//GEN-LAST:event_campoQtdImagensKeyReleased

    private void botaoLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoLimparActionPerformed

        imagens = new ImagemModel();
        tabelaImagens.setModel(imagens);

        TableColumn col0 = tabelaImagens.getColumnModel().getColumn(0);
        int tam = 30;
        col0.setPreferredWidth(tam);
        col0.setMaxWidth(tam);
        col0.setMinWidth(tam);

        TableColumn col1 = tabelaImagens.getColumnModel().getColumn(1);
        tam = 25;
        col1.setPreferredWidth(tam);
        col1.setMaxWidth(tam);
        col1.setMinWidth(tam);

        TableColumn col2 = tabelaImagens.getColumnModel().getColumn(2);
        tam = 0;
        col2.setPreferredWidth(tam);
        col2.setMaxWidth(tam);
        col2.setMinWidth(tam);
        col2.setResizable(false);

        col2 = tabelaImagens.getTableHeader().getColumnModel().getColumn(2);
        col2.setPreferredWidth(tam);
        col2.setMaxWidth(tam);
        col2.setMinWidth(tam);
        col2.setResizable(false);

        TableCellRenderer renderer = new ImagemCellRenderer();
        for (int c = 0; c < tabelaImagens.getColumnCount(); c++) {
            tabelaImagens.setDefaultRenderer(tabelaImagens.getColumnClass(c), renderer);
        }

        tabelaImagens.getColumnModel().getColumn(1).setCellRenderer(new ImagemCellRendererCheck());

        tabelaImagens.getColumnModel().getColumn(3).setCellRenderer(new ImagemCellRendererBar());
    }//GEN-LAST:event_botaoLimparActionPerformed

    private void botaoProcurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoProcurarActionPerformed
        try {
            JFileChooser jfcDiretorio = new JFileChooser();
            jfcDiretorio.setDialogTitle("Escolha a pasta padrão:");
            jfcDiretorio.setCurrentDirectory(new File(campoPastaPadrao.getText()));
            jfcDiretorio.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            int result = jfcDiretorio.showOpenDialog(new javax.swing.JFrame());
            if (result == 0) {
                String dir = jfcDiretorio.getSelectedFile().toString();
                campoPastaPadrao.setText(dir);
                Config.getInstance().setPastaPadrao(dir);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }//GEN-LAST:event_botaoProcurarActionPerformed

    private void botaoFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoFecharActionPerformed
        this.dispose();
    }//GEN-LAST:event_botaoFecharActionPerformed

    private void tabelaImagensMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaImagensMouseMoved
        int row = tabelaImagens.rowAtPoint(new Point(evt.getX(), evt.getY()));
        if (row != tempRow) {
            ImagemModel model = (ImagemModel) tabelaImagens.getModel();

            Imagem img = (Imagem) model.getObjectAt(row);

            tabelaImagens.setToolTipText("<html><body><img src=\""+
                    img.getCacheGoogle()+"\"></body></html>");

            tempRow = row;
        }
    }//GEN-LAST:event_tabelaImagensMouseMoved
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar barra;
    private javax.swing.JButton botaoBaixar;
    private javax.swing.JButton botaoFechar;
    private javax.swing.JButton botaoLimpar;
    private javax.swing.JButton botaoPesquisar;
    private javax.swing.JButton botaoProcurar;
    private javax.swing.JTextField campoPastaPadrao;
    private javax.swing.JTextField campoPesquisa;
    private javax.swing.JFormattedTextField campoQtdImagens;
    private javax.swing.JEditorPane editorHtml;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelVelocidade;
    private javax.swing.JTabbedPane painelTabulado;
    private javax.swing.JTable tabelaImagens;
    // End of variables declaration//GEN-END:variables
}
